package com.wanshi.servlet;

import com.wanshi.dao.UserDao;
import com.wanshi.entity.User;
import com.wanshi.service.UserService;
import com.wanshi.utils.MD5Util;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    private UserService userService = new UserService();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");


        HttpSession session = request.getSession();
        String ma = (String) session.getAttribute("ma");

        String yan = request.getParameter("yan");

        if(ma == null || !ma.equals(yan)){
            request.setAttribute("error","验证码输入错误!");
            request.getRequestDispatcher("/login.jsp").forward(request,response);
            return;
        }

        String username = request.getParameter("username");

        String password = request.getParameter("password");
        String md5Str = MD5Util.getMD5Str(password);
        User user = userService.findUserByNameAndPsd(username, md5Str);

        if(user == null){
            //response.getWriter().write("用户名或密码错误");
            request.setAttribute("error","用户名或密码错误!");
            request.getRequestDispatcher("/login.jsp").forward(request,response);
        }else{
            //登录成功
            Cookie cookie = new Cookie("JSESSIONID",session.getId());
            cookie.setPath(request.getContextPath());
            cookie.setMaxAge(1800);
            response.addCookie(cookie);
            session.setAttribute("user",user);

            response.sendRedirect(request.getContextPath()+"/index.jsp");
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

